﻿using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Diagnostics;
using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;

namespace MQ_WechatCustomContact
{
	/// <summary>
	/// 根据手机号获取user
	/// </summary>
	public class MobileToUser: ICustomContact
	{
		private string logTitle = "mobiletouser";
		private  ConsumeConfig _consumeConfig;
		private RequestAppSecret _appSecret;
		private string _SoftwareVersion = string.Empty;
		public MobileToUser(RequestAppSecret appSecret)
        {
			_appSecret = appSecret;
			_SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });

		}
		public  async Task Excute(ConsumeConfig consumeConfig)
		{
			_consumeConfig = consumeConfig;

			var stopwatch = new Stopwatch();
			stopwatch.Start();
            //拉数据
            try
            {
                var list = await PullData();
				if (list == null || list.Count == 0)
				{
                    stopwatch.Stop();
                    Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】没有拉取到数据哟");
                    return;
                }
                //根据手机号获取员工userId
                await GetUserIdByMobile(list);

                //获取跟进人
                var userDic = await GetFollerList();

                //推数据
                await Push(list, userDic);
                stopwatch.Stop();
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
            }
            catch (Exception ex)
            {
				if (stopwatch.IsRunning)
				{
					stopwatch.Stop();
				}
				Console.WriteLine($"【{logTitle}】:{ex.Message}");
			}
		}
		/// <summary>
		/// 接数据
		/// </summary>
		/// <returns></returns>
		private async Task<List<UserOutput>> PullData()
		{
			var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"is_user_contact",0 }
			};
			var result = await new ApiRequestClient(_appSecret).
				GetResponse< List<UserOutput>>(_consumeConfig.Domain,
				"wxgroup.account.manager.boundwxaccountoperlist", dic);
			if (result.Success)
			{
				var ret = (IResponse<List<UserOutput>>)result;
				return ret.Content;
			}
			return null;

		}
		/// <summary>
		/// 根据手机号获取员工userId
		/// </summary>
		/// <returns></returns>
		private async Task GetUserIdByMobile(List<UserOutput> list)
		{
			int pageSize = 50;
			int pageIndex = list.Count / pageSize;
			if (list.Count % pageSize != 0) pageIndex++;
			for (int i = 0; i < pageIndex; i++)
			{
				int count = pageSize;
				if (pageSize * (i + 1) > list.Count)
				{
					count = list.Count % pageSize;
				}

				var waitlist = list.GetRange(pageSize * i, count);
				var mobiles = new Dictionary<string, object>();
				foreach(var u in waitlist)
				{
					if (u.Mobile== "15258597381")
					{
						mobiles.Add(u.ManagerId.ToString(), u.Mobile);
					}
					//mobiles.Add(u.ManagerId.ToString(), u.Mobile);
				}
				
				var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"db_id",_consumeConfig.DBId },
				{"para",HttpUtility.UrlEncode(Json.ToJson(mobiles)) }
			};
				var result = await new ApiRequestClient(_appSecret).
				GetResponse<JObject>(_consumeConfig.WechatDomain,
				"bind_user_relation", dic, "/wx/bind_user_relation", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
				if (!result.Success) continue;

				var ret = ((IResponse<JObject>)result).Content;
				if (!ret.ContainsKey("users")) continue;
				var arr = ret["users"] as JArray;

				foreach (JObject item in arr)
				{
					var entity = new UserOutput();
					entity.SetValues(item.ToObject<Dictionary<string, object>>());

					var one = list.Find(s => s.ManagerId == entity.ManagerId);
					if (one == null) continue;
					one.WXUserId = entity.WXUserId;
				}

			}		

		}
		/// <summary>
		/// 获取跟进人
		/// </summary>
		/// <returns></returns>
		private async Task<List<string>> GetFollerList()
		{
			var userDic = new List<string>();
			var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"db_id",_consumeConfig.DBId },
			};
			var result = await new ApiRequestClient(_appSecret).
			GetResponse<List<string>>(_consumeConfig.WechatDomain,
			string.Empty, dic, "/wx/customer/foller_list", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } }, 10000);
			if (result.Success)
			{
				userDic = ((IResponse<List<string>>)result).Content;
			}
			return userDic;

		}

		/// <summary>
		/// 推数据
		/// </summary>
		/// <param name="list"></param>
		/// <returns></returns>
		private async Task Push(List<UserOutput> list, List<string> userDic)
		{
			var li = list.FindAll(s => !string.IsNullOrEmpty(s.WXUserId));

			StringBuilder stringBuilder = new StringBuilder();
			foreach (var item in li)
			{
				if (userDic.Contains(item.WXUserId))
				{
					item.IsUserContact = true;
					await AsyncContactWay(item);
				}
				stringBuilder.AppendLine($"<oper>{item.ToXml()}</oper>");
			}
			
			var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"XML",($"<root>{stringBuilder.ToString()}</root>").SafeString() }
			};
			var result=await new ApiRequestClient(_appSecret).
		PostBinary<JObject>(_consumeConfig.Domain,
		"wxgroup.account.manager.updateboundwxaccountstate", dic);
			if (!result.Success)
			{
				Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString()}");
			}

		}
		private async Task AsyncContactWay(UserOutput item)
		{
			//二维码
			if (string.IsNullOrEmpty(item.WXConfigId))
			{
				await AddContactWay(item, 2);
			}
			else
			{
				await UpldateContactWay(item, item.WXConfigId, 2);
			}
			//小程序
			if (string.IsNullOrEmpty(item.WXMinConfigId))
			{
				await AddContactWay(item, 1);
			}
			else
			{
				await UpldateContactWay(item, item.WXMinConfigId, 1);
			}
		}
		/// <summary>
		/// 获取跟进人
		/// </summary>
		/// <returns></returns>
		private async Task AddContactWay(UserOutput userOutput,int scene)
		{
			var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"db_id",_consumeConfig.DBId },
				{"fk_flag",2 },
				{"user_id",userOutput.WXUserId },
				{"scene",scene },
			};
			var result = await new ApiRequestClient(_appSecret).
			GetResponse<JObject>(_consumeConfig.WechatDomain,
			string.Empty, dic, "/wx/customer/add_contact_way", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } });
			if (!result.Success) return;

			var obj = ((IResponse<JObject>)result).Content;
			if (scene == 2)
			{
				userOutput.WXConfigId = obj["WXConfigId"].ToString();
				userOutput.WXQRcode = obj["WXQRcode"].ToString();
			}
			else
			{
				userOutput.WXMinConfigId = obj["WXConfigId"].ToString();
			}
		}
		private async Task UpldateContactWay(UserOutput userOutput,string configId, int scene)
		{
			var dic = new Dictionary<string, object>()
			{
				{"fk_id",_consumeConfig.FKId },
				{"db_id",_consumeConfig.DBId },
				{"fk_flag",2 },
				{"user_id",userOutput.WXUserId },
				{"scene",scene },
				{"config_id",configId },
			};
			await new ApiRequestClient(_appSecret).
			GetResponse<JObject>(_consumeConfig.WechatDomain,
			string.Empty, dic, "/wx/customer/update_contact_way", new Dictionary<string, string>() { { "api-version", "2.0" }, { "version", _SoftwareVersion } });

		}
	}
}
